package com.cq.hd.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.common.enums.ResponseEnums;
import com.cq.hd.common.enums.biz.AgentStateEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.RedisUtil;
import com.cq.hd.common.utils.StringUtils;
import com.cq.hd.member.api.dto.*;
import com.cq.hd.member.api.vo.*;
import com.cq.hd.member.mapper.*;
import com.cq.hd.member.po.*;
import com.cq.hd.member.service.TbBusinessAgentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cq.hd.member.service.TbBusinessGroupService;
import com.cq.hd.system.api.HfApi;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 商家经纪人关联表 服务实现类
 * </p>
 *
 * @author mYunYu
 * @since 2023-11-21
 */
@Slf4j
@Service
public class TbBusinessAgentServiceImpl extends ServiceImpl<TbBusinessAgentMapper, TbBusinessAgentPo> implements TbBusinessAgentService {

    @Autowired
    private TbAppUserMapper appUserMapper;

    @Autowired
    private TbBusinessMapper businessMapper;

    @Autowired
    private TbBusinessAgentBindRecordMapper businessAgentBindRecordMapper;

    @Autowired
    private TbBusinessGroupMapper businessGroupMapper;

    @Autowired
    private TbBusinessAgentCommissionRecordMapper businessAgentCommissionRecordMapper;

    @Autowired
    private TbBusinessAgentMapper businessAgentMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private HfApi hfApi;

    @Autowired
    private TbAgentBindApplyMapper tbAgentBindApplyMapper;

    @Autowired
    private TbAgentUnBindApplyMapper tbAgentUnBindApplyMapper;

    @Autowired
    private TbBusinessGroupService businessGroupService;

    // 经纪人列表
    @Override
    public Page<AgentPageVo> pageAgent(AgentPageDto agentPageDto) {
        String startTime = agentPageDto.getStartTime();
        String endTime = agentPageDto.getEndTime();
        if (!StringUtils.isBlank(startTime) && startTime.length() != 19) {
            Throw.isBusinessException("日期格式错误");
        }
        if (!StringUtils.isBlank(endTime) && endTime.length() != 19) {
            Throw.isBusinessException("日期格式错误");
        }

        PageHelper.startPage(agentPageDto.getPageNum(), agentPageDto.getPageSize());
        List<AgentPageVo> agentPageVos = appUserMapper.listAgentByDto(agentPageDto);
        if (!CollectionUtils.isEmpty(agentPageVos)) {
            List<Long> userIds = agentPageVos.stream().map(AgentPageVo::getId).collect(Collectors.toList());

            // 根据经纪人id查询tb_business_agent表获取分销金额等数据，并累加
            Map<Long, List<TbBusinessAgentPo>> businessAgentMap = new HashMap<>();
            List<TbBusinessAgentPo> tbBusinessAgentPos = businessAgentMapper.selectList(new QueryWrapper<TbBusinessAgentPo>().eq("del_state", 0)
                    .in("user_id", userIds));
            if (!CollectionUtils.isEmpty(tbBusinessAgentPos)) {
                businessAgentMap = tbBusinessAgentPos.stream().collect(Collectors.groupingBy(TbBusinessAgentPo::getUserId));
            }

            for (AgentPageVo agentPageVo : agentPageVos) {
                // 总分销订单数
                int totalOrderCount = 0;
                // 总分销订单金额
                BigDecimal totalOrderAmt = BigDecimal.ZERO;
                // 关联策划人数
                int relationBusinessCount = 0;
                // 累计分销佣金
                BigDecimal totalCommission = BigDecimal.ZERO;
                // 累计提现佣金
                BigDecimal totalWithdrawalCommission = BigDecimal.ZERO;

                Long id = agentPageVo.getId();
                List<TbBusinessAgentPo> tbBusinessAgentPoList = businessAgentMap.get(id);
                if (!CollectionUtils.isEmpty(tbBusinessAgentPoList)) {
                    relationBusinessCount = tbBusinessAgentPoList.size();
                    for (TbBusinessAgentPo tbBusinessAgentPo : tbBusinessAgentPoList) {
                        totalOrderCount += tbBusinessAgentPo.getTotalOrderCount();
                        totalOrderAmt = totalOrderAmt.add(tbBusinessAgentPo.getTotalOrderAmt());
                        totalCommission = totalCommission.add(tbBusinessAgentPo.getTotalCommission());
                        totalWithdrawalCommission = totalWithdrawalCommission.add(tbBusinessAgentPo.getTotalWithdrawalCommission());
                    }
                }

                if (agentPageVo.getAgentId() > 0) {
                    agentPageVo.setAgentLevel(2);
                }
                agentPageVo.setTotalOrderCount(totalOrderCount);
                agentPageVo.setTotalOrderAmt(totalOrderAmt);
                agentPageVo.setRelationBusinessCount(relationBusinessCount);
                agentPageVo.setTotalCommission(totalCommission);
                agentPageVo.setTotalWithdrawalCommission(totalWithdrawalCommission);
            }
        }
        PageInfo<AgentPageVo> pageInfo = new PageInfo<>(agentPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public List<BusinessAgentVo> listByBusinessIds(List<Long> businessIds) {
        return baseMapper.listByBusinessIds(businessIds);
    }

//    @Override
//    public Boolean bind(BusinessAgentBindDto businessAgentBindDto) {
//        String code = businessAgentBindDto.getCode();
//        Long userId = businessAgentBindDto.getUserId();
//        if (userId == null || StringUtils.isBlank(code)) {
//            Throw.isBusinessException("邀请链接错误");
//        }
//
//        String personName = businessAgentBindDto.getPersonName();
//        if (StringUtils.isBlank(personName)) {
//            Throw.isBusinessException("请输入姓名");
//        }
//
//        String certNo = businessAgentBindDto.getCertNo();
//        if (StringUtils.isBlank(certNo)) {
//            Throw.isBusinessException("请输入身份证号");
//        }
//
//        Integer certValidityType = businessAgentBindDto.getCertValidityType();
//        if (certValidityType == null || CertValidityTypeEnum.typeOfValue(certValidityType) == null) {
//            Throw.isBusinessException("请选择证件有效期");
//        }
//
//        String certBeginDate = businessAgentBindDto.getCertBeginDate();
//        if (CertValidityTypeEnum.NO.getValue().equals(certValidityType)) {
//            String certEndDate = businessAgentBindDto.getCertEndDate();
//            if (StringUtils.isBlank(certBeginDate)) {
//                Throw.isBusinessException("请选择证件有效期开始日期");
//            }
//
//            if (StringUtils.isBlank(certEndDate)) {
//                Throw.isBusinessException("请选择证件有效期截止日期");
//            }
//
//            LocalDate legalCertBeginLocalDate = null;
//            LocalDate legalCertEndLocalDate = null;
//            try {
//                legalCertBeginLocalDate = LocalDateUtil.toLocalDate(certBeginDate, Constant.YYYY_MM_DD);
//            } catch (Exception e) {
//                Throw.isBusinessException("证件有效期开始日期选择错误");
//            }
//
//            try {
//                legalCertEndLocalDate = LocalDateUtil.toLocalDate(certEndDate, Constant.YYYY_MM_DD);
//            } catch (Exception e) {
//                Throw.isBusinessException("证件有效期截止日期选择错误");
//            }
//
//            if (legalCertEndLocalDate.compareTo(legalCertBeginLocalDate) <= 0) {
//                Throw.isBusinessException("证件有效期截止日期必须大于开始日期");
//            }
//        } else {
//            // 如果是长期有效，法人证件有效期开始日期也不能为空
//            if (StringUtils.isBlank(certBeginDate)) {
//                Throw.isBusinessException("请选择证件有效期开始日期");
//            }
//
//            LocalDate legalCertBeginLocalDate = null;
//            try {
//                legalCertBeginLocalDate = LocalDateUtil.toLocalDate(certBeginDate, Constant.YYYY_MM_DD);
//            } catch (Exception e) {
//                Throw.isBusinessException("证件有效期开始日期选择错误");
//            }
//        }
//
//        TbAppUserPo tbAppUserPo = appUserMapper.selectById(userId);
//        if (tbAppUserPo == null || tbAppUserPo.getDelState() != 0) {
//            Throw.isBusinessException("未找到用户数据");
//        }
//
//        List<TbBusinessPo> businessPos = businessMapper.selectList(new QueryWrapper<TbBusinessPo>().eq("del_state", 0)
//                .eq("invite_code", code));
//        if (CollectionUtils.isEmpty(businessPos)) {
//            Throw.isBusinessException("未找到商家");
//        }
//
//        TbBusinessPo tbBusinessPo = businessPos.get(0);
//        Long id = tbBusinessPo.getId();
//        String hfMerchantNo = tbBusinessPo.getHfMerchantNo();
//
//        if (tbBusinessPo.getUserId().equals(userId)) {
//            log.error("受邀用户与商家是同一个用户，userId：{}", userId);
//            Throw.isBusinessException("不能成为商家自己的经纪人");
//        }
//
//        TbBusinessAgentPo businessAgentPo = new TbBusinessAgentPo();
//        List<TbBusinessAgentPo> tbBusinessAgentPos = baseMapper.selectList(new QueryWrapper<TbBusinessAgentPo>()
//                .eq("del_state", 0)
//                .eq("user_id", userId).eq("business_id", id));
//        if (!CollectionUtils.isEmpty(tbBusinessAgentPos)) {
//            boolean exist = false;
//            for (TbBusinessAgentPo tbBusinessAgentPo : tbBusinessAgentPos) {
//                if (tbBusinessAgentPo.getDelState() == 0) {
//                    exist = true;
//                }
//            }
//
//            if (exist) {
//                Throw.isBusinessException(ResponseEnums.BINDED_BUSINESS);
//            }
//
//            businessAgentPo = tbBusinessAgentPos.get(0);
//        }
//
//        String getHfId = tbAppUserPo.getHfId();
//        // 是否是经纪人(1-不是，2-是)
//        if (tbAppUserPo.getAgentState() == 1 && !StringUtils.isBlank(hfMerchantNo) && StringUtils.isBlank(getHfId)) {
//            //  调用汇付个人用户基本信息开户接口
//            HfAgentUserEnterApply hfAgentUserEnterApply = new HfAgentUserEnterApply();
//            hfAgentUserEnterApply.setPersonName(businessAgentBindDto.getPersonName());
//            hfAgentUserEnterApply.setCertNo(businessAgentBindDto.getCertNo());
//            hfAgentUserEnterApply.setCertValidityType(businessAgentBindDto.getCertValidityType());
//            hfAgentUserEnterApply.setCertBeginDate(businessAgentBindDto.getCertBeginDate());
//            hfAgentUserEnterApply.setCertEndDate(businessAgentBindDto.getCertEndDate());
//            hfAgentUserEnterApply.setMobileNo(tbAppUserPo.getMobile());
//            JSONObject jsonObject = hfApi.agentUserInvite(hfAgentUserEnterApply).unpack();
//            if (jsonObject == null) {
//                Throw.isBusinessException("绑定失败，请联系客服");
//            }
//
//            JSONObject dataJSONObject = jsonObject.getJSONObject("data");
//            String respCode = dataJSONObject.getString("resp_code");
//            String respDesc = dataJSONObject.getString("resp_desc");
//            if (!"00000000".equals(respCode) && !"00000100".equals(respCode) && !"00000102".equals(respCode) && !"90000000".equals(respCode)) {
//                Throw.isBusinessException(respDesc);
//            }
//
//            String hfId = dataJSONObject.getString("huifu_id");
//            if (!StringUtils.isBlank(hfId)) {
//                tbAppUserPo.setHfId(hfId);
//            }
//            tbAppUserPo.setRealName(businessAgentBindDto.getPersonName());
//            tbAppUserPo.setCertNo(businessAgentBindDto.getCertNo());
//            tbAppUserPo.setCertValidityType(businessAgentBindDto.getCertValidityType());
//            tbAppUserPo.setCertBeginDate(businessAgentBindDto.getCertBeginDate());
//            tbAppUserPo.setCertEndDate(businessAgentBindDto.getCertEndDate());
//        }
//
//        // 查找该商家的默认分组
//        TbBusinessGroupPo businessGroupPo = businessGroupMapper.getDefaultGroup(id);
//        LocalDateTime now = LocalDateTime.now();
//
//        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());
//
//        try {
//            if (businessAgentPo != null && businessAgentPo.getId() != null) {
//                // 如果解绑之后再次绑定，之前设置的分组和佣金都需要重新设置
//                businessAgentPo.setGroupId(businessGroupPo.getId());
//                businessAgentPo.setCommissionRate(BigDecimal.ZERO);
//                // 更新状态
//                businessAgentPo.setDelState(0);
//                businessAgentPo.setUpdateTime(now);
//
//                // 需要增加关联商家数
//                int update = baseMapper.updateBind(businessAgentPo);
//                if (update == 0) {
//                    Throw.isBusinessException("受邀失败");
//                }
//
//                // 新增专属佣金设置记录
//                TbBusinessAgentCommissionRecordPo tbBusinessAgentCommissionRecordPo = new TbBusinessAgentCommissionRecordPo();
//                tbBusinessAgentCommissionRecordPo.setBusinessId(businessAgentPo.getBusinessId());
//                tbBusinessAgentCommissionRecordPo.setUserId(businessAgentPo.getUserId());
//                tbBusinessAgentCommissionRecordPo.setCommissionRate(businessAgentPo.getCommissionRate());
//                tbBusinessAgentCommissionRecordPo.setCreateBusinessId(businessAgentPo.getBusinessId());
//                tbBusinessAgentCommissionRecordPo.setCreateTime(now);
//                tbBusinessAgentCommissionRecordPo.setUpdateTime(now);
//                int insert = businessAgentCommissionRecordMapper.insert(tbBusinessAgentCommissionRecordPo);
//                if (insert == 0) {
//                    Throw.isBusinessException("受邀失败");
//                }
//            } else {
//                TbBusinessAgentPo tbBusinessAgentPo = new TbBusinessAgentPo();
//                tbBusinessAgentPo.setUserId(userId);
//                tbBusinessAgentPo.setBusinessId(id);
//                tbBusinessAgentPo.setGroupId(businessGroupPo.getId());
//                tbBusinessAgentPo.setTotalOrderCount(0);
//                tbBusinessAgentPo.setTotalOrderAmt(BigDecimal.ZERO);
//                tbBusinessAgentPo.setRelationBusinessCount(1);
//                tbBusinessAgentPo.setTotalCommission(BigDecimal.ZERO);
//                tbBusinessAgentPo.setTotalWithdrawalCommission(BigDecimal.ZERO);
//                tbBusinessAgentPo.setCreateTime(now);
//                int insert = baseMapper.insert(tbBusinessAgentPo);
//                if (insert == 0) {
//                    Throw.isBusinessException("受邀失败");
//                }
//            }
//
//            // 是否是经纪人(1-不是，2-是)
//            tbAppUserPo.setAgentState(2);
//            tbAppUserPo.setUpdateTime(now);
//            int update = appUserMapper.updateById(tbAppUserPo);
//            if (update == 0) {
//                Throw.isBusinessException("受邀失败");
//            }
//
//            // 添加商家经纪人绑定记录
//            TbBusinessAgentBindRecordPo tbBusinessAgentBindRecordPo = new TbBusinessAgentBindRecordPo();
//            tbBusinessAgentBindRecordPo.setUserId(userId);
//            tbBusinessAgentBindRecordPo.setBusinessId(id);
//            tbBusinessAgentBindRecordPo.setBindTime(now);
//            tbBusinessAgentBindRecordPo.setCreateTime(now);
//            int insert = businessAgentBindRecordMapper.insert(tbBusinessAgentBindRecordPo);
//            if (insert <= 0) {
//                Throw.isBusinessException("受邀失败");
//            }
//
//            // 更新未分组的成员个数
////            update = businessGroupMapper.addNum(businessGroupPo.getId(), 1);
////            if (update == 0) {
////                Throw.isBusinessException("受邀失败");
////            }
//
//            transactionManager.commit(transaction);
//        } catch (Exception e) {
//            //回滚事务
//            transactionManager.rollback(transaction);
//            log.error("<经纪人绑定商家>事务异常回滚", e);
//            Throw.isBusinessException("受邀失败");
//        }
//
//        // 将最新的用户数据缓存Redis
//        String userInfoRedis = redisUtil.get(String.format(RedisKeyConstant.USER_INFO_KEY, userId));
//        if (!StringUtils.isNullOrEmpty(userInfoRedis)) {
//            UserInfo userInfo = JSON.parseObject(userInfoRedis, UserInfo.class);
//            // 是否是经纪人(1-不是，2-是)
//            userInfo.setAgentState(2);
//
//            redisUtil.set(String.format(RedisKeyConstant.USER_INFO_KEY, userId), JSON.toJSONString(userInfo), Constant.USER_LOGIN_TIMEOUT, TimeUnit.SECONDS);
//        }
//
//        return true;
//    }

    @Override
    public Boolean unBind(BusinessAgentUnBindDto businessAgentUnBindDto) {
        Long id = businessAgentUnBindDto.getId();
        Long businessId = businessAgentUnBindDto.getBusinessId();

        TbBusinessPo tbBusinessPo = businessMapper.selectById(businessId);
        if (tbBusinessPo == null || tbBusinessPo.getDelState() != 0) {
            Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
        }

        List<TbBusinessAgentPo> tbBusinessAgentPos = baseMapper.selectList(new QueryWrapper<TbBusinessAgentPo>()
                .eq("del_state", 0)
                .eq("user_id", id)
                .eq("business_id", businessId));
        if (CollectionUtils.isEmpty(tbBusinessAgentPos)) {
            Throw.isBusinessException("未找到绑定关系");
        }

        LocalDateTime now = LocalDateTime.now();

        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());

        try {
            TbBusinessAgentPo tbBusinessAgentPo = tbBusinessAgentPos.get(0);
            tbBusinessAgentPo.setDelState(1);
            tbBusinessAgentPo.setUpdateTime(now);
            int update = baseMapper.updateUnBind(tbBusinessAgentPo);
            if (update == 0) {
                Throw.isBusinessException("解绑失败");
            }

            // 更新商家经纪人绑定记录中的解绑时间
            List<TbBusinessAgentBindRecordPo> tbBusinessAgentBindRecordPos = businessAgentBindRecordMapper
                    .selectList(new QueryWrapper<TbBusinessAgentBindRecordPo>()
                            .eq("del_state", 0)
                            .eq("user_id", id)
                            .eq("business_id", businessId)
                            .orderByDesc("bind_time"));
            if (!CollectionUtils.isEmpty(tbBusinessAgentBindRecordPos)) {
                TbBusinessAgentBindRecordPo tbBusinessAgentBindRecordPo = tbBusinessAgentBindRecordPos.get(0);
                tbBusinessAgentBindRecordPo.setUnbindTime(now);
                tbBusinessAgentBindRecordPo.setUpdateTime(now);
                businessAgentBindRecordMapper.updateById(tbBusinessAgentBindRecordPo);
            }

            // 更新对应分组的分组成员个数
            businessGroupMapper.updateNum(tbBusinessAgentPo.getGroupId());

            // 更新商家经纪人数量
            businessMapper.updateAgentCount(businessId);

            transactionManager.commit(transaction);
        } catch (Exception e) {
            //回滚事务
            transactionManager.rollback(transaction);
            log.error("<商家解绑经纪人>事务异常回滚", e);
            Throw.isBusinessException("解绑失败");
        }

        return true;
    }

    @Override
    public BusinessAgentIndexVo businessAgentIndex(BusinessAgentIndexDto businessAgentIndexDto) {
        BusinessAgentIndexVo businessAgentIndexVo = new BusinessAgentIndexVo();

        Long userId = businessAgentIndexDto.getUserId();
        Long businessId = businessAgentIndexDto.getBusinessId();
        businessAgentIndexVo.setAgentLevel(businessAgentIndexDto.getAgentLevel());
        if (businessId != null && businessId > 0) {
            // 我的经纪人数量
            Integer count = baseMapper.selectCount(new QueryWrapper<TbBusinessAgentPo>()
                    .eq("del_state", 0)
                    .eq("business_id", businessId));
            businessAgentIndexVo.setAgentCount(count == null ? 0 : count);
            businessAgentIndexVo.setAgentShowState(true);

            TbBusinessPo businessPo = businessMapper.selectById(businessId);
            if (businessPo == null || businessPo.getDelState() != 0) {
                Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
            }
            businessAgentIndexVo.setMaxInviteAgentCount(businessPo.getMaxInviteAgentCount());
        } else {
            TbAppUserPo tbAppUserPo = appUserMapper.selectById(userId);
            if (tbAppUserPo == null) {
                Throw.isBusinessException("账号不存在");
            }
            // 我的经纪人数量
            Integer count = baseMapper.selectCount(new QueryWrapper<TbBusinessAgentPo>()
                    .eq("del_state", 0)
                    .eq("agent_id", userId));
            businessAgentIndexVo.setAgentCount(count == null ? 0 : count);

            if (businessAgentIndexVo.getAgentCount() > 0 || businessAgentIndexVo.getAgentLevel() == 1) {
                businessAgentIndexVo.setAgentShowState(true);
            }
        }
        // 我的策划人数量
        Integer businessCount = baseMapper.selectCount(new QueryWrapper<TbBusinessAgentPo>()
                .eq("del_state", 0)
                .eq("agent_id", 0)
                .eq("user_id", userId));
        businessAgentIndexVo.setBusinessCount(businessCount == null ? 0 : businessCount);
        if (businessAgentIndexVo.getBusinessCount() > 0) {
            businessAgentIndexVo.setBusinessShowState(true);
        }

        // 待审核经纪人数量
        Integer agentWaitAuditCount = tbAgentBindApplyMapper.getWaitAuditCount(userId);
        // 一级经纪人，需要加上解绑申请待审核数量
        if (businessAgentIndexVo.getAgentLevel() == 1) {
            Integer unbindCount = tbAgentUnBindApplyMapper.getWaitAuditCount(userId);
            if (unbindCount != null && unbindCount > 0) {
                agentWaitAuditCount += unbindCount;
            }
        }
        businessAgentIndexVo.setWaitAuditAgentCount(agentWaitAuditCount);

        return businessAgentIndexVo;
    }

    @Override
    public Page<MyAgentPageVo> pageMyAgent(MyAgentPageDto myAgentPageDto) {
        PageHelper.startPage(myAgentPageDto.getPageNum(), myAgentPageDto.getPageSize());
        List<MyAgentPageVo> agentPageVos = baseMapper.lisMyAgentByDto(myAgentPageDto);
        PageInfo<MyAgentPageVo> pageInfo = new PageInfo<>(agentPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public Page<MyBusinessPageVo> pageMyBusiness(MyBusinessPageDto myBusinessPageDto) {
        Long userId = myBusinessPageDto.getUserId();
        if (userId == null || userId <= 0) {
            Throw.isBusinessException(ResponseEnums.USER_ACCESS_DENIED);
        }

        PageHelper.startPage(myBusinessPageDto.getPageNum(), myBusinessPageDto.getPageSize());
        List<MyBusinessPageVo> agentPageVos = baseMapper.lisMyBusinessByDto(myBusinessPageDto);
        PageInfo<MyBusinessPageVo> pageInfo = new PageInfo<>(agentPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public Boolean saveAgentCommission(BusinessAgentCommissionSaveDto businessAgentCommissionSaveDto) {
        List<BusinessAgentCommissionDto> businessAgentCommissions = businessAgentCommissionSaveDto.getBusinessAgentCommissions();
        if (CollectionUtils.isEmpty(businessAgentCommissions)) {
            return true;
        }

        Long agentId = businessAgentCommissionSaveDto.getAgentId();
        Long businessId = businessAgentCommissionSaveDto.getBusinessId();
        if (businessId == null || businessId < 0) {
            businessId = 0L;
        }
        if (agentId == null || agentId < 0) {
            agentId = 0L;
        }

        // 校验专属佣金是否合法
        for (BusinessAgentCommissionDto businessAgentCommission : businessAgentCommissions) {
            BigDecimal commissionRate = businessAgentCommission.getCommissionRate();
            if(commissionRate == null || commissionRate.compareTo(BigDecimal.ZERO) == 0){
                continue;
            }

            if (commissionRate.compareTo(new BigDecimal("0.1")) < 0 || commissionRate.compareTo(new BigDecimal("100")) > 0) {
                Throw.isBusinessException("设置的专属佣金比例范围是0.1~100");
            }
        }

        LocalDateTime now = LocalDateTime.now();

        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());

        try {
            for (BusinessAgentCommissionDto businessAgentCommission : businessAgentCommissions) {
                BigDecimal commissionRate = businessAgentCommission.getCommissionRate();
                Long getUserId = businessAgentCommission.getUserId();

                CommissionRateUpdateDto commissionRateUpdateDto = new CommissionRateUpdateDto();
                commissionRateUpdateDto.setBusinessId(businessId);
                commissionRateUpdateDto.setAgentId(agentId);
                commissionRateUpdateDto.setUserId(getUserId);
                commissionRateUpdateDto.setCommissionRate(commissionRate);
                int count = baseMapper.updateCommissionRate(commissionRateUpdateDto);
                if (count > 0) {
                    // 新增专属佣金设置记录
                    TbBusinessAgentCommissionRecordPo tbBusinessAgentCommissionRecordPo = new TbBusinessAgentCommissionRecordPo();
                    tbBusinessAgentCommissionRecordPo.setBusinessId(businessId);
                    tbBusinessAgentCommissionRecordPo.setUserId(getUserId);
                    tbBusinessAgentCommissionRecordPo.setCommissionRate(commissionRate);
                    tbBusinessAgentCommissionRecordPo.setCreateBusinessId(businessId);
                    tbBusinessAgentCommissionRecordPo.setAgentId(agentId);
                    tbBusinessAgentCommissionRecordPo.setCreateTime(now);
                    tbBusinessAgentCommissionRecordPo.setUpdateTime(now);
                    int insert = businessAgentCommissionRecordMapper.insert(tbBusinessAgentCommissionRecordPo);
                    if (insert == 0) {
                        log.error("新增专属佣金记录失败，tbBusinessAgentCommissionRecordPo：{}", JSON.toJSONString(tbBusinessAgentCommissionRecordPo));
                        Throw.isBusinessException("设置失败");
                    }
                }
            }

            transactionManager.commit(transaction);
        } catch (Exception e) {
            //回滚事务
            transactionManager.rollback(transaction);
            log.error("<设置经纪人专属佣金>事务异常回滚", e);
            Throw.isBusinessException("设置失败");
        }

        return true;
    }

    @Override
    public Page<BusinessAgentCommissionPageVo> pageAgentCommission(BusinessAgentCommissionPageDto businessAgentCommissionPageDto) {
        PageHelper.startPage(businessAgentCommissionPageDto.getPageNum(), businessAgentCommissionPageDto.getPageSize());
        List<BusinessAgentCommissionPageVo> businessAgentCommissionPageVos = baseMapper.lisAgentCommissionByDto(businessAgentCommissionPageDto);
        PageInfo<BusinessAgentCommissionPageVo> pageInfo = new PageInfo<>(businessAgentCommissionPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public Page<BusinessGroupAgentPageVo> pageBusinessGroupAgent(BusinessGroupAgentPageDto businessGroupAgentPageDto) {
        if (businessGroupAgentPageDto.getGroupId() == null || businessGroupAgentPageDto.getGroupId() <= 0) {
            Long businessId = businessGroupAgentPageDto.getBusinessId();
            Long agentId = businessGroupAgentPageDto.getAgentId();

            // 商家或者经纪人默认分组
            TbBusinessGroupPo businessGroupPo = businessGroupService.getDefaultGroupWithInit(businessId, agentId);

            // 只返回未分组的成员
            businessGroupAgentPageDto.setGroupId(businessGroupPo.getId());
        }

        PageHelper.startPage(businessGroupAgentPageDto.getPageNum(), businessGroupAgentPageDto.getPageSize());
        List<BusinessGroupAgentPageVo> businessGroupAgentPageVos = baseMapper.lisBusinessGroupAgentByDto(businessGroupAgentPageDto);
        PageInfo<BusinessGroupAgentPageVo> pageInfo = new PageInfo<>(businessGroupAgentPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public Boolean deleteBusinessGroupAgent(Long id, Long businessId, Long agentId) {
        TbBusinessAgentPo tbBusinessAgentPo = baseMapper.selectById(id);
        if (tbBusinessAgentPo == null || tbBusinessAgentPo.getDelState() != 0) {
            Throw.isBusinessException("未找到分组成员数据");
        }

        if (!tbBusinessAgentPo.getBusinessId().equals(businessId) && !tbBusinessAgentPo.getAgentId().equals(agentId)) {
            Throw.isBusinessException("未找到分组成员数据");
        }
        Long groupId = tbBusinessAgentPo.getGroupId();

        // 查找该商家或者经纪人的默认分组
        TbBusinessGroupPo businessGroupPo = businessGroupService.getDefaultGroupWithInit(businessId, agentId);

        if (groupId.equals(businessGroupPo.getId())) {
            Throw.isBusinessException("不能删除未分组成员数据");
        }

        // 将删除的分组成员划分到未分组中
        tbBusinessAgentPo.setGroupId(businessGroupPo.getId());
        tbBusinessAgentPo.setUpdateTime(LocalDateTime.now());
        int update = baseMapper.updateById(tbBusinessAgentPo);
        if (update == 0) {
            Throw.isBusinessException("删除失败");
        }

        // 更新分组成员数
        businessGroupMapper.updateNum(id);

        return true;
    }

    @Override
    public BusinessAgentVo getBusinessAgentById(Long businessId, Long userId) {
        return baseMapper.getBusinessAgentById(businessId, userId);
    }

    @Override
    public List<BusinessSelectAgentGroupVo> listBusinessSelectAgent(Long userId, Long businessId) {
        if (businessId == null || businessId <= 0) {
            if (userId == null || userId <= 0) {
                Throw.isBusinessException(ResponseEnums.USER_ACCESS_DENIED);
            }

            // 根据userId查询商家id
            List<TbBusinessPo> tbBusinessPos = businessMapper.selectList(new QueryWrapper<TbBusinessPo>().eq("del_state", 0)
                    .eq("user_id", userId));
            if (CollectionUtils.isEmpty(tbBusinessPos)) {
                // 如果不是商家，则返回空
                Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
            }

            businessId = tbBusinessPos.get(0).getId();
        }

        List<BusinessSelectAgentGroupMapperVo> businessSelectAgentGroupMapperVos = baseMapper.listBusinessSelectAgent(businessId);
        if (CollectionUtils.isEmpty(businessSelectAgentGroupMapperVos)) {
            return new ArrayList<>();
        }

        List<BusinessSelectAgentGroupVo> businessSelectAgentGroupVos = new ArrayList<>();

        Map<Long, List<BusinessSelectAgentGroupMapperVo>> businessSelectAgentGroupMapperMap = businessSelectAgentGroupMapperVos.stream()
                .collect(Collectors.groupingBy(BusinessSelectAgentGroupMapperVo::getGroupId));
        for (Long key : businessSelectAgentGroupMapperMap.keySet()) {
            List<BusinessSelectAgentGroupMapperVo> businessSelectAgentGroupMapperVoList = businessSelectAgentGroupMapperMap.get(key);

            List<BusinessSelectAgentVo> businessSelectAgentVos = new ArrayList<>();
            for (BusinessSelectAgentGroupMapperVo businessSelectAgentGroupMapperVo : businessSelectAgentGroupMapperVoList) {
                BusinessSelectAgentVo businessSelectAgentVo = new BusinessSelectAgentVo();
                businessSelectAgentVo.setUserId(businessSelectAgentGroupMapperVo.getUserId());
                businessSelectAgentVo.setNickName(businessSelectAgentGroupMapperVo.getNickName());
                businessSelectAgentVo.setAvatar(businessSelectAgentGroupMapperVo.getAvatar());

                businessSelectAgentVos.add(businessSelectAgentVo);
            }

            BusinessSelectAgentGroupVo businessSelectAgentGroupVo = new BusinessSelectAgentGroupVo();
            businessSelectAgentGroupVo.setGroupId(key);
            businessSelectAgentGroupVo.setGroupName(businessSelectAgentGroupMapperVoList.get(0).getGroupName());
            businessSelectAgentGroupVo.setBusinessSelectAgents(businessSelectAgentVos);

            businessSelectAgentGroupVos.add(businessSelectAgentGroupVo);
        }

        return businessSelectAgentGroupVos;
    }

    @Override
    public List<BusinessAgentVo> listByDto(BusinessAgentDto businessAgentDto) {
        return baseMapper.listByDto(businessAgentDto);
    }

    @Override
    public Integer getNewCountByDate(String startTime, String endTime) {
        return baseMapper.selectCount(new QueryWrapper<TbBusinessAgentPo>().eq("del_state", 0)
                .ge("create_time", startTime).le("create_time", endTime));
    }

    @Override
    public Boolean updateBusinessAgentOrder(UpdateBusinessAgentOrderDto updateBusinessAgentOrderDto) {
        return baseMapper.updateBusinessAgentOrder(updateBusinessAgentOrderDto);
    }

    @Override
    public Boolean updateSubAgentOrder(UpdateSubAgentOrderDto updateSubAgentOrderDto) {
        return baseMapper.updateSubAgentOrder(updateSubAgentOrderDto);
    }

    // 批量删除分组成员，批量移动分组成员
    @Override
    public Boolean batchChangeGroup(BusinessGroupBatchChangeGroupDto businessGroupBatchChangeGroupDto) {
        Long businessId = businessGroupBatchChangeGroupDto.getBusinessId();
        Long agentId = businessGroupBatchChangeGroupDto.getAgentId();

        List<Long> userIds = businessGroupBatchChangeGroupDto.getUserIds();
        if (CollectionUtils.isEmpty(userIds)) {
            Throw.isBusinessException("请选择要操作的经纪人");
        }
        List<TbBusinessAgentPo> tbBusinessAgentPos = businessAgentMapper.selectList(new QueryWrapper<TbBusinessAgentPo>()
                .eq("del_state", 0)
                .eq("business_id", businessId)
                .eq("agent_id", agentId)
                .in("user_id", userIds));
        if (CollectionUtils.isEmpty(tbBusinessAgentPos)) {
            Throw.isBusinessException("操作失败，没有找到选中的经纪人");
        }
        List<Long> userIdList = tbBusinessAgentPos.stream()
                .map(TbBusinessAgentPo::getUserId)
                .collect(Collectors.toList());
        businessGroupBatchChangeGroupDto.setUserIds(userIdList);

        Long groupId = businessGroupBatchChangeGroupDto.getGroupId();
        if (groupId == null || groupId <= 0) {
            // 查找该商家或者经纪人的默认分组
            TbBusinessGroupPo businessGroupPo = businessGroupService.getDefaultGroupWithInit(businessId, agentId);
            groupId = businessGroupPo.getId();
        } else {
            // 判断分组id是不是属于该商家的
            TbBusinessGroupPo businessGroupPo = businessGroupMapper.getGroupById(groupId);
            if (businessGroupPo == null || (!Objects.equals(businessGroupPo.getBusinessId(), businessId) && !Objects.equals(businessGroupPo.getAgentId(), agentId))) {
                Throw.isBusinessException("分组不存在");
            }
        }
        businessGroupBatchChangeGroupDto.setGroupId(groupId);

        List<Long> groupIdList = tbBusinessAgentPos.stream()
                .map(TbBusinessAgentPo::getGroupId)
                .distinct()
                .collect(Collectors.toList());
        groupIdList.add(groupId);

        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());

        try {
            baseMapper.updateGroupId(businessGroupBatchChangeGroupDto);
            for (Long groupId1 : groupIdList) {
                businessGroupMapper.updateNum(groupId1);
            }

            transactionManager.commit(transaction);
        } catch (Exception e) {
            //回滚事务
            transactionManager.rollback(transaction);
            log.error("<批量操作分组成员失败>事务异常回滚", e);
            Throw.isBusinessException("操作失败");
        }

        return true;
    }

    // 我的上级经纪人
    @Override
    public MyAgentVo myParentAgent(Long userId) {
        MyAgentVo myAgentVo = baseMapper.myParentAgent(userId);
        if (myAgentVo != null) {
            // 看看是不是解绑中
            TbAgentUnBindApplyPo po = tbAgentUnBindApplyMapper.getWaitAuditByApplyUserId(userId);
            if (po != null) {
                myAgentVo.setState(2);
            }
        }

        return myAgentVo;
    }

    @Override
    public List<Long> myBusinessIds(Long userId) {
        return baseMapper.myBusinessIds(userId);
    }

    // 获取商家跟一级经纪人的佣金比例，-1表示不是分销关系
    @Override
    public BigDecimal getAgentCommissionRate(Long userId, Long businessId) {
        return getCommissionRate(businessId, 0L, userId);
    }

    // 获取一级经纪人跟二级经纪人的佣金比例，-1表示不是分销关系
    @Override
    public BigDecimal getSubAgentCommissionRate(Long userId, Long agentId) {
        return getCommissionRate(0L, agentId, userId);
    }

    private BigDecimal getCommissionRate(Long businessId, Long agentId, Long userId) {
        // 获取绑定关系
        TbBusinessAgentPo businessAgentPo = baseMapper.getBusinessAgentRecord(businessId, agentId, userId);
        // 不是绑定关系，返回 -1，表示不能拿佣金
        if (businessAgentPo == null) {
            return BigDecimal.valueOf(-1);
        }

        // 如果有设置专属佣金，优先返回专属佣金
        BigDecimal commissionRate = businessAgentPo.getCommissionRate();
        if (commissionRate != null && commissionRate.compareTo(BigDecimal.ZERO) > 0) {
            return commissionRate;
        }

        // 看看有没有配置分组佣金
        TbBusinessGroupPo businessGroupPo = businessGroupMapper.getGroupById(businessAgentPo.getGroupId());
        if (businessGroupPo == null || businessGroupPo.getCommissionRate() == null || businessGroupPo.getCommissionRate().compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO;
        }

        return businessGroupPo.getCommissionRate();
    }

    @Override
    public Map<Long, BigDecimal> getAgentCommissionRateByBusinessIds(Long userId, List<Long> businessIds) {
        Map<Long, BigDecimal> map = new HashMap<>();

        List<AgentCommissionRateVo> agentCommissionRateVos = baseMapper.listAgentCommissionRateByBusinessIds(userId, businessIds);
        for (AgentCommissionRateVo agentCommissionRateVo : agentCommissionRateVos) {
            BigDecimal commissionRate = agentCommissionRateVo.getCommissionRate();
            // 专属佣金
            if (commissionRate != null && commissionRate.compareTo(BigDecimal.ZERO) > 0) {
                map.put(agentCommissionRateVo.getBusinessId(), commissionRate);
                continue;
            }

            BigDecimal groupCommissionRate = agentCommissionRateVo.getGroupCommissionRate();
            // 分组佣金
            if (groupCommissionRate != null && groupCommissionRate.compareTo(BigDecimal.ZERO) > 0) {
                map.put(agentCommissionRateVo.getBusinessId(), groupCommissionRate);
                continue;
            }
            // 默认就是0
            map.put(agentCommissionRateVo.getBusinessId(), BigDecimal.ZERO);
        }

        return map;
    }
}
